package com.lanou.tipsy.fragment.recommend;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import com.facebook.drawee.view.SimpleDraweeView;
import com.lanou.tipsy.R;
import com.lanou.tipsy.adapter.recommend.CarouselAdapter;
import com.lanou.tipsy.adapter.recommend.HotSongsAdapter;
import com.lanou.tipsy.adapter.recommend.NewestListAdapter;
import com.lanou.tipsy.adapter.recommend.SongsRecommendAdapter;
import com.lanou.tipsy.base.BaseFragment;
import com.lanou.tipsy.base.Constants;
import com.lanou.tipsy.data.MyEventBus;
import com.lanou.tipsy.entity.playerList.personal.PersonalList;
import com.lanou.tipsy.entity.recommend.carousel.Carousel;
import com.lanou.tipsy.entity.recommend.carousel.CarouselPicEntity;
import com.lanou.tipsy.entity.recommend.guess.singer.RightListEntity;
import com.lanou.tipsy.entity.recommend.guess.singer.SongGuessRight;
import com.lanou.tipsy.entity.recommend.guess.songlist.GuessListEntity;
import com.lanou.tipsy.entity.recommend.guess.songlist.SongGuess;
import com.lanou.tipsy.entity.recommend.hot_songs.SongHotRecommend;
import com.lanou.tipsy.entity.recommend.hot_songs.SongListEntity;
import com.lanou.tipsy.entity.recommend.newest_recommend.newSongsRecommend.NewSongsRecommend;
import com.lanou.tipsy.entity.recommend.newest_recommend.newestSongsList.NewestList;
import com.lanou.tipsy.entity.recommend.songlist_recommend.SongsRecommend;
import com.lanou.tipsy.entity.recommend.songlist_recommend.SongsRecommendListEntity;
import com.lanou.tipsy.tools.listview.NoScrollGridView;
import com.lanou.tipsy.tools.listview.NoScrollListView;
import com.lanou.tipsy.tools.volley.ResponseErrorListener;
import com.lanou.tipsy.tools.volley.VolleySingleton;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Random;

import de.greenrobot.event.EventBus;

/**
 * Created by FengJun on 15/10/20.
 * 推荐
 */
public class RecommendFragment extends BaseFragment
        implements ViewPager.OnPageChangeListener, View.OnTouchListener, View.OnClickListener, AdapterView.OnItemClickListener {
    private Context mContext;
    //推荐tag
    public static final String TAG = "RecommendFragment";
    //网络请求
    private VolleySingleton volleySingleton;//创建volleySingleton对象
    private ResponseErrorListener errorListener;
    //轮播图
    private ViewPager viewPager;//定义一个viewPager
    private ArrayList<CarouselPicEntity> picEntities; //实体类集合
    private CarouselAdapter carAdapter;//轮播图适配器
    private LinearLayout linearLayout; //定义线性布局
    private Runnable vpRunnable; //定义线程
    private Handler handler; //定义handler
    private boolean flag = false;// 定义一个标志位,用于标识页面是否切换,判断轮播图是否继续轮播
    private FrameLayout frameLayout;
    //猜你喜欢
    private Uri uri;//定义Uri
    private String url;//定义url
    private SimpleDraweeView draw_re_list_today; //今日歌单图片(左)
    private SimpleDraweeView draw_re_list_today_top;//右上
    private SimpleDraweeView draw_re_list_today_bottom;//右下
    private TextView tv_re_guess;//今日歌单标题
    private ArrayList<GuessListEntity> guessListEntities;
    private SimpleDraweeView draw_re_singer_today;//歌手图片
    private TextView tv_re_singer;//歌手
    private ArrayList<RightListEntity> singerListEntities;
    private RelativeLayout relativeLayout;
    private NoScrollListView hotSongsLv;
    //我的歌曲列表
    private ArrayList<PersonalList> personalLists;
    //热门歌曲推荐
    private HotSongsAdapter adapter;
    private ArrayList<SongListEntity> songlistEntities;
    //歌单推荐
    private NoScrollGridView gv_recommend_songs;
    private ArrayList<SongsRecommendListEntity> srl;
    private SongsRecommendAdapter recommendAdapter;
    private int finalToday;
    //最新歌曲->每日新歌推荐
    private SimpleDraweeView newSongsIv;
    private NewSongsRecommend newSongsRecommend;
    //最新歌曲->歌曲列表
    private ArrayList<NewestList.PlazeAlbumListEntity.RMEntity.AlbumListEntity.ListEntity> lists;
    private NoScrollGridView newestListGv;
    private NewestListAdapter listAdapter;


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.mContext = context;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fr_recommend, null);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //初始化控件
        initView(getView());
        //解析的方法
        carouselRequest();//轮播图
        guessListRequest();//猜你喜欢->今日歌单
        guessSingerRequest();//猜你喜欢->歌手
        hotSongsRequest();//热门歌曲推荐
        newestSongsRequest();//最新歌曲->每日新歌推荐
        newestListRequest();//最新歌曲->新歌推荐列表
        songListRecommendRequest();//歌单推荐
        //监听
        click();
    }

    private void initView(View view) {
        viewPager = (ViewPager) view.findViewById(R.id.vp_recommend);
        draw_re_list_today = (SimpleDraweeView) view.findViewById(R.id.draw_re_list_today);
        draw_re_list_today_top = (SimpleDraweeView) view.findViewById(R.id.draw_re_list_today_top);
        draw_re_list_today_bottom = (SimpleDraweeView) view.findViewById(R.id.draw_re_list_today_bottom);
        tv_re_guess = (TextView) view.findViewById(R.id.tv_re_guess);
        draw_re_singer_today = (SimpleDraweeView) view.findViewById(R.id.draw_re_singer_today);
        tv_re_singer = (TextView) view.findViewById(R.id.tv_re_singer);
        relativeLayout = (RelativeLayout) view.findViewById(R.id.rl_guess);
        frameLayout = (FrameLayout) view.findViewById(R.id.fl_re_singer_today);
        hotSongsLv = (NoScrollListView) view.findViewById(R.id.lv_hot_songs);
        gv_recommend_songs = (NoScrollGridView) view.findViewById(R.id.gv_recommend_songs);
        newSongsIv = (SimpleDraweeView) view.findViewById(R.id.iv_newest_songs);
        newestListGv = (NoScrollGridView) view.findViewById(R.id.gv_newestList);
        //初始化
        volleySingleton = VolleySingleton.getInstance();
        errorListener = new ResponseErrorListener();
        handler = new Handler();
        initViewPager(view);
    }

    //监听的方法
    private void click() {
        //猜你喜欢->今日歌单->监听
        relativeLayout.setOnClickListener(this);
        frameLayout.setOnClickListener(this);
        newSongsIv.setOnClickListener(this);
        newestListGv.setOnItemClickListener(this);
        gv_recommend_songs.setOnItemClickListener(this);
    }

    //监听方法的回调
    @Override
    public void onClick(View v) {
        FragmentManager manager = getActivity().getSupportFragmentManager();
        FragmentTransaction transaction;
        Bundle bundle;
        switch (v.getId()) {
            case R.id.rl_guess://猜你喜欢->今日歌单
                TodaySongsListFragment fragment = new TodaySongsListFragment();
                getActivity().overridePendingTransition
                        (R.anim.translate_enter_in, R.anim.translate_enter_out);
                bundle = new Bundle();
                bundle.putSerializable("guessListEntities", guessListEntities);
                fragment.setArguments(bundle);
                transaction = manager.beginTransaction();
                transaction.add(R.id.fl_main, fragment);
                transaction.addToBackStack(null);
                transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
                transaction.commit();
                break;
            case R.id.fl_re_singer_today://猜你喜欢->歌手
                TodaySingerFragment singerFragment = new TodaySingerFragment();
                bundle = new Bundle();
                bundle.putSerializable("todaySinger", singerListEntities);
                bundle.putInt("today", finalToday);
                singerFragment.setArguments(bundle);
                transaction = manager.beginTransaction();
                transaction.add(R.id.fl_main, singerFragment);
                transaction.addToBackStack(null);
                transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
                transaction.commit();
                break;
            case R.id.iv_newest_songs://最新歌曲->每日新歌推荐
                EverydayNeweastSongsFragment songsFragment = new EverydayNeweastSongsFragment();
                bundle = new Bundle();
                bundle.putSerializable("newsongs", newSongsRecommend);
                Log.i("test", TAG + "新歌信息" + newSongsRecommend + "");
                songsFragment.setArguments(bundle);
                transaction = manager.beginTransaction();
                transaction.add(R.id.fl_main, songsFragment);
                transaction.addToBackStack(null);
                transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
                transaction.commit();
                break;
        }
    }

    /**
     * 解析
     */
    //轮播图:解析
    private void carouselRequest() {
        StringRequest request = new StringRequest(Constants.CAROUSEL_PIC_URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.i("test", TAG + "RecommendFragment" + "这里有木有数据" + response);
                Carousel carousel = JSON.parseObject(response, Carousel.class);
                picEntities = carousel.getPic();
                getPoint();
                carAdapter = new CarouselAdapter(picEntities, mContext);
                viewPager.setAdapter(carAdapter);
                //将当前位置设在中间,可以左右滑动
                initRunnable(picEntities.size());
                viewPager.setCurrentItem(5000000);
            }
        }, errorListener);
        volleySingleton.addQueue(request, TAG);
    }

    //猜你喜欢->今日歌单:解析
    private void guessListRequest() {
        StringRequest request = new StringRequest(Constants.GUESS_SONGS_LISTS, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                SongGuess guess = JSON.parseObject(response, SongGuess.class);
                guessListEntities = guess.getResult().getList();
                Random random = new Random();
                //图片1
                int i = random.nextInt(guessListEntities.size() - 1);
                url = guessListEntities.get(i).getPic_big();
                if (url != null) {
                    uri = Uri.parse(url);
                    draw_re_list_today.setImageURI(uri);
                }
                //图片2
                int x = random.nextInt(guessListEntities.size() - 1);
                url = guessListEntities.get(x).getPic_big();
                if (url != null) {
                    uri = Uri.parse(url);
                    draw_re_list_today_top.setImageURI(uri);
                }
                //图片3
                int y = random.nextInt(guessListEntities.size() - 1);
                url = guessListEntities.get(y).getPic_big();
                if (url != null) {
                    uri = Uri.parse(url);
                    draw_re_list_today_bottom.setImageURI(uri);
                }
                tv_re_guess.setText("今日歌单");
            }
        }, errorListener);
        volleySingleton.addQueue(request, TAG);
    }

    //猜你喜欢->歌手:解析
    private void guessSingerRequest() {
        StringRequest request = new StringRequest(Constants.GUESS_SINGERS, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                SongGuessRight right = JSON.parseObject(response, SongGuessRight.class);
                singerListEntities = right.getResult().getList();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Calendar calendar = Calendar.getInstance();
                calendar.add(calendar.DATE, 0);
                SimpleDateFormat dd = new SimpleDateFormat("dd");
                String dayNum = dd.format(calendar.getTime());
                String num = dayNum.substring(1, 2);
                int today = 0;
                if (num.equals("0")) {
                    today = 0;
                } else if (num.equals("1")) {
                    today = 1;
                } else if (num.equals("2")) {
                    today = 2;
                } else if (num.equals("3")) {
                    today = 3;
                } else if (num.equals("4")) {
                    today = 4;
                } else if (num.equals("5")) {
                    today = 5;
                } else if (num.equals("6")) {
                    today = 6;
                } else if (num.equals("7")) {
                    today = 7;
                } else if (num.equals("8")) {
                    today = 8;
                } else if (num.equals("9")) {
                    today = 9;
                }

                finalToday = today;

                url = singerListEntities.get(finalToday).getAvatar_big();
                if (url != null) {
                    uri = Uri.parse(url);
                    draw_re_singer_today.setImageURI(uri);
                }
                tv_re_singer.setText(singerListEntities.get(finalToday).getName());
            }
        }, errorListener);
        volleySingleton.addQueue(request, TAG);
    }

    //热门歌曲推荐:解析
    private void hotSongsRequest() {
        StringRequest request = new StringRequest(Constants.HOT_SONGS_URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                SongHotRecommend recommend = JSON.parseObject(response, SongHotRecommend.class);
                songlistEntities = recommend.getContent().get(0).getSong_list();
                adapter = new HotSongsAdapter(songlistEntities, mContext);
                hotSongsLv.setAdapter(adapter);
                //点击行布局发送数据到service
                hotSongsLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        //To-Do 传递数据
                        SongListEntity entity = (SongListEntity) parent.getItemAtPosition(position);
                        Log.i("Test", "RecommendFragment->被点击的歌曲的名字:" + entity.getTitle());
                        personalLists = new ArrayList<>();
                        for (SongListEntity songlistEntity : songlistEntities) {
                            PersonalList personalList = new PersonalList();
                            personalList.setSingerName(songlistEntity.getAuthor());
                            personalList.setSongsUrl(songlistEntity.getSong_id());
                            String uuu = songlistEntity.getSong_id();
                            Log.i("huoqu",uuu);
                            personalList.setTag("网络歌曲");
                            personalList.setSongTitle(songlistEntity.getTitle());
                            personalList.setPicture(songlistEntity.getPic_big());
                            personalLists.add(personalList);
                        }
                        //发送数据到EventBus
                        EventBus.getDefault().post(new MyEventBus.NetSongs(personalLists, position));
                        Log.i("Test", "RecommendFragment->输出点击的歌曲:" + position);
                    }
                });
            }
        }, errorListener);
        volleySingleton.addQueue(request, TAG);
    }

    //最新歌曲->每日新歌推荐:解析
    private void newestSongsRequest() {
        StringRequest request = new StringRequest(Constants.NEWEST_SONG_URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                newSongsRecommend = JSON.parseObject(response, NewSongsRecommend.class);
                String url = newSongsRecommend.getCollection().getPic();
                if (url != null) {
                    Uri uri = Uri.parse(url);
                    newSongsIv.setImageURI(uri);
                }
            }
        }, errorListener);
        volleySingleton.addQueue(request, TAG);
    }

    //最新歌曲->新歌推荐列表:解析
    private void newestListRequest() {
        StringRequest request = new StringRequest(Constants.NEWEST_LIST_URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                NewestList newestList = JSON.parseObject(response, NewestList.class);
                lists = newestList.getPlaze_album_list().getRM().getAlbum_list().getList();
                Log.i("test", TAG + " 最新歌单" + lists + "");
                listAdapter = new NewestListAdapter(lists, mContext);
                newestListGv.setAdapter(listAdapter);
            }
        }, errorListener);
        volleySingleton.addQueue(request, TAG);
    }

    //歌单推荐:解析
    private void songListRecommendRequest() {
        StringRequest request = new StringRequest(Constants.SONG_LIST_RECOMMEND_URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                SongsRecommend songsRecommend = JSON.parseObject(response, SongsRecommend.class);
                srl = songsRecommend.getContent().getList();
                recommendAdapter = new SongsRecommendAdapter(getContext(), srl);
                gv_recommend_songs.setAdapter(recommendAdapter);

            }
        }, errorListener);
        volleySingleton.addQueue(request, TAG);
    }

    /**
     * 轮播图小圆点
     */
    //初始化存放小圆点的容器
    private void initViewPager(View view) {
        viewPager.addOnPageChangeListener(this);
        viewPager.setOnTouchListener(this);
        linearLayout = (LinearLayout) view.findViewById(R.id.li_point);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            handler.removeCallbacks(vpRunnable);
            handler.postDelayed(vpRunnable, Constants.TIME);
        } else {
            handler.removeCallbacks(vpRunnable);
        }
        return false;
    }

    //轮播图上面的小圆点
    public void getPoint() {
        for (int i = 0; i < picEntities.size(); i++) {
            ImageView img = new ImageView(mContext);
            ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(25, 25);
            img.setPadding(8, 8, 8, 8);

            img.setScaleType(ImageView.ScaleType.FIT_XY);
            img.setLayoutParams(lp);
            if (i == 0) {
                img.setImageResource(R.mipmap.point_grey);
            } else {
                img.setImageResource(R.mipmap.point_white);
            }
            linearLayout.addView(img);
        }
    }

    //viewpager监听的回调
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        //小圆点的改变
        for (int i = 0; i < picEntities.size(); i++) {
            ImageView img = (ImageView) linearLayout.getChildAt(i);
            img.setImageResource(R.mipmap.point_white);
        }
        ImageView img = (ImageView) linearLayout.getChildAt(position % picEntities.size());
        img.setImageResource(R.mipmap.point_grey);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    //开启子线程开始轮播
    protected void initRunnable(final int size) {
        vpRunnable = new Runnable() {
            @Override
            public void run() {
                int index = viewPager.getCurrentItem();
                //使图片轮播,每一次==1
                viewPager.setCurrentItem(++index);
                if (flag) {
                    handler.postDelayed(vpRunnable, Constants.TIME);
                }
            }
        };
        if (flag) {
            handler.postDelayed(vpRunnable, Constants.TIME);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.i("test", "RecommendFragment->onResume()");
        flag = true;
        handler.postDelayed(vpRunnable, Constants.TIME);
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.i("test", "RecommendFragment->onStop()");
        flag = false;
        handler.removeCallbacks(vpRunnable);
        volleySingleton.removeRequest(TAG);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        FragmentManager manager = getActivity().getSupportFragmentManager();
        Bundle bundle;
        FragmentTransaction transaction;
        //最新歌曲推荐页面跳转
        if (parent == newestListGv) {

            //http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.6.5.2&method=baidu.ting.album.getAlbumInfo&format=json&album_id=
            String url = lists.get(position).getAlbum_id();
            NewRecommendFragment singerFragment = new NewRecommendFragment();
            bundle = new Bundle();
            //向新页面传递URL
            bundle.putString("url", url);
            singerFragment.setArguments(bundle);
            transaction = manager.beginTransaction();
            transaction.add(R.id.fl_main, singerFragment);
            transaction.addToBackStack(null);
            transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
            transaction.commit();
            Log.i("test", TAG + "动画,,,进入");
        }
        // //推荐页面跳转
        else if (parent == gv_recommend_songs) {
            String url = srl.get(position).getListid();
            SongListRecommendFragment singerFragment = new SongListRecommendFragment();
            bundle = new Bundle();
            //向新页面传递URL
            bundle.putString("url", url);
            singerFragment.setArguments(bundle);
            transaction = manager.beginTransaction();
            transaction.add(R.id.fl_main, singerFragment);
            transaction.addToBackStack(null);
            transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
            transaction.commit();
        }
    }
}